Exercises
Compose Tweet
In older versions of Twitter, a number showed you how many characters you had left to use in your message:
In the playground below, we've recreated this UI, but our implementation isn't as nice as it could be. Your job is to refactor this code, to improve it.
Acceptance Criteria:
- The number of characters remaining should be derived from the
messages
state, not stored in a state variable. - No effects should be used.
- Bonus question: Can you think of any reasons why an effect is not the right tool for this problem?
Code Playground
Solution:
Checkout flow
In this exercise, we're working with a checkout flow. The “shopping cart” we saw back in Module 1 now includes some info underneath about the price.
Unfortunately, this code has a pretty big bug: removing an item from the cart doesn't update the subtotal/tax/total values!
Your mission is to fix this bug.
Acceptance Criteria:
- The numbers at the bottom of the page (Subtotal / Taxes / Total) should recalculate when removing an item from the cart.
- You should remove any state variables that aren't necessary. Derive state whenever possible.
Code Playground
Solution:
Thermostat
Below, you'll find a thermostat that lets us set the temperature. We can also switch between Celsius and Fahrenheit modes for displaying the current temperature.
With the current code, we're storing two state variables, one for the celsius
value, and one for the fahrenheit
value.
Your task is to simplify this code by having a single state variable that holds information about the temperature (as well as a 2nd state variable for the displayed format).
This is a surprisingly tricky challenge. I thought this would be pretty straightforward, and I struggled to come up with a solution I was 100% happy with. Please don't be discouraged if you can't solve this one!
Acceptance Criteria:
- A single state variable should be used to keep track of the thermostat's current temperature.
- The and buttons should increase/decrease the current temperature by 1 degree.
- Note: It doesn't matter what the current mode is. Whether we're in “celsius” mode or “fahrenheit” mode, these buttons should increase/decrease the displayed temperature by 1 (eg. from 77°F to 78°F, or from 25°C to 26°C).
- You can use the helper functions
convertToCelsius
andconvertToFahrenheit
to convert between units.
Code Playground
Solution: